%endPos = findEndSq(startPos,piece)
%   This function finds the first square closing bracket (']') from the 
%   starting position in the string piece and returns it's position.
%   Because the string 'piece' has been cut in the function 'readPiece' in
%   which this function is called, the search starts at the first element
%   of 'piece'.

%%
function endPos = findEndSq(startPos,piece)
%% Main

%Set starting position to 1
j = 1;

%Set 'found' to false
found = false;

%While the end of the string 'piece' has not been reached check the next
%element in 'piece' for a square closing bracket. Set 'found' to true when
%this element has been found to stop the loop.
while j <= length(piece) && ~found
    if piece(j) == ']'
        found = true;
    else
        j = j+1;
    end
end

%If the square closing bracket still hasn't been found return this error:
if ~found
    error(['A square bracket pair was found to be incomplete, remaining'...
        'piece to be read was: ' piece])
else %Create 'endPos' to return
    endPos = startPos + j - 1;
end

%% End
end